package com.wn.utils;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtil {

    private static final String secret = "Zirrom";

    public static String createToken(String user,int minute) {
        JwtBuilder jwtBuilder = Jwts.builder();
        //设置 头部
        jwtBuilder.setHeaderParam("alg", "HS256");
        jwtBuilder.setHeaderParam("typ", "JWT");
        //设置载荷
        jwtBuilder.setIssuer("wnwzj");
        jwtBuilder.setSubject("ziroom");
        long expire = minute * 60 * 1000;
        jwtBuilder.setExpiration(new Date(new Date().getTime() + expire));
        //自定义信息
        jwtBuilder.claim("user", user);

        //设置 签名qrw

        jwtBuilder.signWith(SignatureAlgorithm.HS256, secret);


        String token = jwtBuilder.compact();
        return token;
    }

    public static Claims parseToken(String token) {
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(secret).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
    }

    public static String getAccount(String token) {
        if(token != null){
            JwtParser parser = Jwts.parser();
            Jws<Claims> claimsJws = parser.setSigningKey(secret).parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            return (String) body.get("user");
        }
        return null;

    }
}

